package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.Constant;
import com.example.demo.dao.AdRepository;
import com.example.demo.model.entity.AdModel;
import com.example.demo.service.impl.AdService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = Constant.API_VERSION + "/ad")
public class AdController {

    @Resource
    AdService adService;

    @Resource
    AdRepository adRepository;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public AdModel save(@RequestBody AdModel model) throws Exception {
        model.setAdId(UUID.randomUUID().toString());
        model.setCreateTime(System.currentTimeMillis());
        if (StringUtils.isNotEmpty(model.getAdContent())) {
            model.setAdType(1);
        }
        return adService.save(model);
    }

    @RequestMapping(value = "/{ad_id}", method = RequestMethod.PUT)
    @ResponseBody
    public AdModel update(@PathVariable(value = "ad_id") String adId, @RequestBody AdModel model) throws Exception {
        AdModel ad = adRepository.findOne(adId);
        if (ad == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "广告不存在"));
        }
        if (StringUtils.isNotEmpty(model.getAdTitle())) {
            ad.setAdTitle(model.getAdTitle());
        }
        if (StringUtils.isNotEmpty(model.getAdDesc())) {
            ad.setAdDesc(model.getAdDesc());
        }
        if (StringUtils.isNotEmpty(model.getAdImg())) {
            ad.setAdImg(model.getAdImg());
        }
        if (StringUtils.isNotEmpty(model.getAdContent())) {
            ad.setAdContent(model.getAdContent());
            ad.setAdType(1);
        }
        if (StringUtils.isNotEmpty(model.getAdCustom())) {
            ad.setAdCustom(model.getAdCustom());
        }
        return adRepository.save(ad);

    }


    @RequestMapping(value = "/{ad_id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void delete(@PathVariable(value = "ad_id") String adId) throws Exception {
        adService.delete(adId);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getAdPage(@RequestParam(value = "page_size", defaultValue = "10") String pageSize, @RequestParam(value = "page_number", defaultValue = "1") String pageNumber,
                                @RequestParam(value = "shop_id", defaultValue = "") final String shopId) throws Exception {
        Page<AdModel> adPage = adService.getAdPage(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(shopId)) {
                    Path<Integer> shopIdPath = root.get("shopId");
                    predicateList.add(criteriaBuilder.equal(shopIdPath, shopId));
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, new PageRequest(Integer.valueOf(pageNumber) - 1, Integer.valueOf(pageSize)));

        JSONObject result = new JSONObject();
        result.put("total", adPage.getTotalElements());
        result.put("items", adPage.getContent());
        return result;
    }

}
